package com.joey.concurrency.example.deadLock;

import lombok.extern.slf4j.Slf4j;

/**
 * 解决死锁
 * 1.顺序加锁，2.时间释放锁，3.死锁检查，发现死锁，回退。继续死锁，对线程进行随机优先级。
 * @Author hyy
 **/
@Slf4j
public class DeadLockExample implements Runnable{

    public int flag = 0;
    //顺序加锁
    //
    private static Object o1 = new Object(),o2 = new Object();

    @Override
    public void run() {
        if(flag == 1){
            synchronized (o1){
                log.info("flag == 1 [o1]");
                try {
                    Thread.sleep(2000);
                    synchronized(o2){
                        log.info("flag == 1 [o2]");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        if(flag == 0){
            synchronized (o2){
                log.info("flag == 0 [o1]");
                try {
                    Thread.sleep(2000);
                    synchronized(o1){
                        log.info("flag == 0 [o2]");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        DeadLockExample lockExample = new DeadLockExample();
        DeadLockExample lockExample2 = new DeadLockExample();
        lockExample.flag = 1;
        lockExample2.flag = 0;
        new Thread(lockExample).start();
        new Thread(lockExample2).start();
    }


}
